package dawnland02.data.map.io.writer;

import org.xml.sax.helpers.AttributesImpl;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.Transformer;
import javax.xml.transform.OutputKeys;
import java.io.File;

import dawnland02.data.map.model.Matrix;
import dawnland02.data.map.model.MatrixCell;
import dawnland02.data.map.io.MatrixXMLTag;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Sep 16, 2009
 * Time: 8:18:46 PM
 */
public class MatrixXMLSAXWriter {

    public void writeMatrix(Matrix matrix, String fileName) {
        try {
            StreamResult streamResult = new StreamResult(new File(fileName));
            SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler();
            Transformer serializer = transformerHandler.getTransformer();
            serializer.setOutputProperty(OutputKeys.VERSION, "1.0");
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
            transformerHandler.setResult(streamResult);

            transformerHandler.startDocument();
            AttributesImpl attributes = new AttributesImpl();
            attributes.addAttribute("", "", MatrixXMLTag.ROWS_ATTRIBUTE.getValue(), "CDATA", matrix.getRows().toString());
            attributes.addAttribute("", "", MatrixXMLTag.COLUMNS_ATTRIBUTE.getValue(), "CDATA", matrix.getColumns().toString());

            transformerHandler.startElement("", "", MatrixXMLTag.MATRIX.getValue(), attributes);
            for (MatrixCell node : matrix.getNodes().values()) {
                attributes.clear();
                attributes.addAttribute("", "", MatrixXMLTag.ID_ATTRIBUTE.getValue(), "CDATA", node.getId().toString());
                attributes.addAttribute("", "", MatrixXMLTag.X_ATTRIBUTE.getValue(), "CDATA", node.getX().toString());
                attributes.addAttribute("", "", MatrixXMLTag.Y_ATTRIBUTE.getValue(), "CDATA", node.getY().toString());
                attributes.addAttribute("", "", MatrixXMLTag.TYPE_ATTRIBUTE.getValue(), "CDATA", node.getType().toString());
                attributes.addAttribute("", "", MatrixXMLTag.ROAD_LEVEL_ATTRIBUTE.getValue(), "CDATA", node.getRoadLevel().toString());
                transformerHandler.startElement("", "", MatrixXMLTag.NODE.getValue(), attributes);
                transformerHandler.endElement("", "", MatrixXMLTag.NODE.getValue());
            }
            transformerHandler.endElement("", "", MatrixXMLTag.MATRIX.getValue());
            transformerHandler.endDocument();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
